/* 
 * Persistence4J - Simple library for data persistence using java
 * Copyright (c) 2010, Avdhesh yadav.
 * http://www.avdheshyadav.com
 * Contact: avdhesh.yadav@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.avdy.p4j.jdbc.dbms;

import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;

import com.avdy.p4j.jdbc.PersistenceConfig;
import com.avdy.p4j.jdbc.dao.AbsPersistenceManager;
import com.avdy.p4j.jdbc.dao.DataFetcherImpl;
import com.avdy.p4j.jdbc.service.DataFetcher;
import com.avdy.p4j.jdbc.service.DataProvider;
import com.avdy.p4j.jdbc.service.DataProviderFactory;
import com.avdy.p4j.jdbc.service.TransactionService;
import com.avdy.p4j.jdbc.transaction.TransactionServiceImpl;

/**
 * 
 * @author Avdhesh Yadav
 *
 */
public class DataProviderFactoryImpl implements DataProviderFactory
{
	private static Logger logger = Logger.getLogger(DataProviderFactoryImpl.class.getName());
	
	private static final long serialVersionUID = 1L;
	
	private DbmsManager m_Manager;
	
	private PersistenceConfig m_Config;
		
	
	/**
	 * 
	 * @param config PersistenceConfig
	 * 
	 */
	public DataProviderFactoryImpl(PersistenceConfig config) 
	{
		logger.info("insdie construtor of DataProviderFactoryImpl");
		m_Config = config;
		m_Manager = DbmsManager.getDbmsManager(m_Config);
	}
	
	
	/**
	 * 
	 * @param database String 
	 * @param dbmsName String
	 * @param isTransactional boolean
	 * 
	 * @return DataProvider
	 * 
	 * @throws Throwable 
	 */
	public DataProvider getDataProvider(String database, String dbmsName, boolean isTransactional)throws Throwable
	{
		DataProvider dataProvider = null;
		Dbms dbms = m_Manager.getDBMS(dbmsName);
		if(dbms.isNewDataSource(database))
		{
			dbms.createDataSource(database, isTransactional);
		}
		//now get the persistence manager from the dbms for this data source.
		AbsPersistenceManager pcManager = dbms.getPCManager(database);
		DataFetcher dataFetcher = new DataFetcherImpl(pcManager);
			
		TransactionService transactionService = null;
		
		if(isTransactional)
		{
			UserTransaction ut = dbms.getTMService(database, isTransactional);
			transactionService  = new TransactionServiceImpl(ut);
		}
			
		dataProvider = new DataProviderImpl(database, dbmsName, dataFetcher, transactionService);
		return dataProvider;
	}
}
